import React from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Upload, message, Modal } from 'antd';
import { getToken } from "@/utils/utils";
import { getOptAuthHeaders } from '@/utils/common';

class PateoUploadImage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      previewVisible: false,
      previewImage: '',
      fileList: [],
    };
    const defaultFileList = props.value;
    if (defaultFileList) {
      const files = this.convertValueToFileList(defaultFileList);
      this.state = { fileList: files };
    }
  }
  componentWillReceiveProps(nextProps) {
    const { value } = this.props;
    if (nextProps.value != value) {
      this.setState({
        fileList: nextProps.value ? this.convertValueToFileList(nextProps.value) : this.state.fileList,
      });
    }
  }
  getBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }
  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
    }
    this.setState({
      previewImage: file.url || file.preview || file.thumbUrl,
      previewVisible: true,
    });
  };
  handleSize = (file) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJPG) {
      message.error('只能上传JPG或PNG图片!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能大于2MB!');
    }
    return isJPG && isLt2M;
  }
  convertValueToFileList = (defaultFileList) => {
    // 获取图片列表
    const files = [];
    if (defaultFileList !== undefined) {
      defaultFileList.split(',').map((val, index) => {
        files.push({
          uid: index,
          name: val,
          status: 'done',
          url: val,
        });
      });
    }
    // 获取图片列表 end
    return files;
  }

  handleChange = (info) => {
    const { onUploadSuccess, formItem, maxCount } = this.props;
    if (info.file.status === 'done') {
      if (info.file.response && info.file.response.statusCode == 0) {
        message.success('图片上传成功');
        // 2.读取响应并显示文件链接
        let newUrl = '';
        info.fileList.map((file, index) => {
          if (index > 0) {
            newUrl = newUrl + ',';
          }
          if (file.response) {
            newUrl = newUrl + file.response.data.fileUrl;
          } else {
            newUrl = newUrl + file.url;
          }
          return file;
        });

        onUploadSuccess(formItem, newUrl);
      } else {
        message.error('图片上传失败');
      }
    } else if (info.file.status === 'error') {
      message.error('图片服务器不可用');
    } else if (info.file.status === 'removed') {
      message.success('图片删除成功');
      if (maxCount != null && maxCount > 1) {
        let newUrl = '';
        info.fileList.map((file, index) => {
          if (index > 0) {
            newUrl = newUrl + ',';
          }
          if (file.response) {
            newUrl = newUrl + file.response.data.fileUrl;
          } else {
            newUrl = newUrl + file.url;
          }
          return file;
        });
        onUploadSuccess(formItem, newUrl);
      } else {
        onUploadSuccess(formItem, '');
      }
    }
    this.setState({ fileList: info.fileList });
  };


  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const { maxCount, text, uploadUrl, headers, accept } = this.props;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div className="ant-upload-text">{text || '上传照片'}</div>
      </div>
    );
    const domain = window.g.url;
    const url = uploadUrl || '/common/upload/img';
    const str = `${domain}${url}`;
    const uploadProps = {
      action: str,
      listType: 'picture-card',
      fileList: this.state.fileList,
      onChange: this.handleChange,
      onPreview: this.handlePreview,
      beforeUpload: this.handleSize,
      accept: accept ?? 'image/*',
      headers: { OptAuthorization: `${getToken()}`, ...getOptAuthHeaders(), ...headers },
    };
    return (
      <div className="clearfix">
        <Upload {...uploadProps}>
          {fileList && fileList.length >= (maxCount || 1) ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          footer={null}
          onCancel={() => this.setState({ previewVisible: false })}
        >
          <img
            alt="example"
            style={{ width: '100%' }}
            src={previewImage}
          />
        </Modal>
      </div>
    );
  }
}
export default PateoUploadImage;
